package com.pktechan.api.utils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by y.zhou on 2016/3/21.
 */
public class ImageCode extends HttpServlet {

    public void doGet(StringBuffer sb, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int width = 130, height = 50;
        //1.在内存生成一个图片
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.得到画笔
        Graphics g = img.getGraphics();
        //3.画一个矩形框
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(0, 0, width, height);
        //4.填充背景
        g.setColor(Color.WHITE);
        g.fillRect(1, 1, width - 1, height - 1);
        //5.画一些干扰线条
        g.setColor(Color.decode("#18A5B5"));
        Random random = new Random();
        for (int i = 1; i <= 10; i++)
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
        //6.画字符串随机的
        g.setColor(Color.decode("#18A5B5"));
        //设置字体
        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 30));
//        StringBuffer sb = new StringBuffer();
        HttpSession session = request.getSession();
        for (int i = 1; i <= 4; i++) {
            String rand = random.nextInt(10) + "";
            sb.append(rand);
            g.drawString(rand, i * 20, 40);
        }
        session.setAttribute("AUTHCODE", sb.toString());
        //清除缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        //7.输出
        response.setContentType("image/jpeg");
        ImageIO.write(img, "jpg", response.getOutputStream());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}
